package com.linkgie.galaxyframework.utils;

import java.util.LinkedList;
import java.util.List;

/**
 * 字符串的格式化器；
 * <p>
 * 
 * 提供纯文本化的表格格式化输出的功能；
 * 
 * @author Hike
 *
 */
public class StringFormatter {

	/**
	 * 定义一个表格的格式化对象；
	 * 
	 * @param cols 列数；
	 * @return
	 */
	public static TableFormat table(int cols) {
		TableFormat table = new TableFormat(cols);
		return table;
	}

	public static class TableFormat {
		public static final int SEPERATOR_WIDTH = 2;

		private int cols;

		private int[] widths;

		private String[] headers;

		private List<String[]> rows = new LinkedList<String[]>();

		private TableFormat(int cols) {
			this.cols = cols;
			this.widths = new int[cols];
		}

		public TableFormat setHeaders(String... headerList) {
			if (headerList != null && headerList.length > 0) {
				headers = new String[cols];
				int headerCount = Math.min(headerList.length, cols);
				for (int i = 0; i < headerCount; i++) {
					headers[i] = headerList[i];

					int colWidth = length(headers[i]);
					widths[i] = Math.max(widths[i], colWidth);
				}
			} else {
				headers = null;
			}

			return this;
		}

		public TableFormat addRow(Object... values) {
			if (values == null || values.length == 0) {
				return this;
			}
			int valueCount = Math.min(values.length, cols);
			String[] strValues = new String[valueCount];
			for (int i = 0; i < strValues.length; i++) {
				strValues[i] = values[i] == null ? "" : String.format("%s", values[i]);
			}
			return addRow(strValues);
		}

		public TableFormat addRow(String... values) {
			if (values == null || values.length == 0) {
				return this;
			}
			String[] row = new String[cols];
			int valueCount = Math.min(values.length, cols);
			for (int i = 0; i < valueCount; i++) {
				row[i] = values[i];

				int colWidth = length(values[i]);
				widths[i] = Math.max(widths[i], colWidth);
			}

			rows.add(row);

			return this;
		}

		public String format() {
			StringBuilder output = new StringBuilder();

			// header;
			if (headers != null) {
				for (int i = 0; i < cols; i++) {
					printCol(headers[i], widths[i], output);
				}
				// 标题换行；
				output.append("\r\n\r\n");
			}

			for (String[] row : rows) {
				for (int i = 0; i < cols; i++) {
					printCol(row[i], widths[i], output);
				}
				// 换行；
				output.append("\r\n");
			}

			return output.toString();
		}

		private int length(String value) {
			if (value == null) {
				return 0;
			}
			int len = 0;
			int chars = value.length();
			char ch;
			for (int i = 0; i < chars; i++) {
				ch = value.charAt(i);
				if (ch < -128 || ch > 127) {
					len += 2;
				} else {
					len += 1;
				}
			}
			return len;
		}

		private void printCol(String content, int width, StringBuilder output) {
			int contentLength = length(content);
			if (content != null) {
				output.append(content);
			}
			int paddingLength = width - contentLength;
			for (int i = 0; i < paddingLength; i++) {
				output.append(' ');
			}
			output.append('\t');
		}
	}

}
